package br.kanban.view.converters;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.persistence.Id;

@FacesConverter(value="entityConverter")
public class EntityConverter implements Converter {  
	  
    public Object getAsObject(FacesContext ctx, UIComponent component, String value) {  
        if (value != null && !value.equals("")) {  
            return component.getAttributes().get(value);  
        }  
        return null;  
    }  
  
    public String getAsString(FacesContext ctx, UIComponent component, Object value) {  
    	String key = "";
    	
    	if(value != null && !value.equals("")){
    		if(getId(value) != null){
    			key = getId(value).toString();
    		}
    		
    		component.getAttributes().put(key, value);
    	}
    	
    	return key;
    }  
  
    public Object getId(Object obj){  
        for (Field field : obj.getClass().getDeclaredFields()) {  
            if ((field.getAnnotation(Id.class)) != null) {  
                StringBuilder fieldName = new StringBuilder( field.getName() );
            	String firstLetter = String.valueOf(fieldName.charAt(0)).toUpperCase();
            	
            	fieldName.replace(0, 1, firstLetter);
            	
           		try {
					return obj.getClass().getMethod("get"+ fieldName.toString()).invoke(obj);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				}
            }  
        }  
        return null;  
    }  
}  